import { Body, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './User.entity';
import { JwtService } from '@nestjs/jwt/dist';
import axios from 'axios';
@Injectable()//它能够处理构造函数的自动依赖注入
export class UserService {

  constructor(
    @InjectRepository(UserEntity)//使用InjectRepository装饰器并引入Repository即可使用typeorm的操作
    private readonly userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService
  ) { }




  async login(code: string) {
    const appId = 'wxa205dbfb55256747'; // 替换为你的微信小程序AppID
    const appSecret = 'b822e7cf94d83a400c8ec7fb8384bfb2'; // 替换为你的微信小程序AppSecret

    // 请求微信接口获取openId和sessionKey
    const response = await axios.get(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`,
    );

    console.log(response)
    const { openid, session_key } = response.data;

    if (!openid || !session_key) {
      throw new Error('Failed to get openid or session_key');
    }
    let user = await this.userRepository.findOne({ where: { openid } });
    if (!user) {
      user = new UserEntity();
      user.openid = openid;
      user.userName = "断弦如雪"
      user.ative = "https://tse4-mm.cn.bing.net/th/id/OIP-C.Y7F_S_i_3BeANSwOgmxSyQHaGy?w=192&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7"
      await this.userRepository.save(user)
    }

    const payload = { openid: user.openid, userid: user.id };
    return {
      access_token: this.jwtService.sign(payload),
      user_id: user.id
    };
  }



  //根据用户id查询用户信息

  async findOne(userId: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        id: userId,
      },
    });
    if (!user) {
      throw new Error('user not found');
    }
    return user;
  }






  async logina(user: any) {
    const payload = { id: user.id, wxID: user.wxID, userName: user.userName, userPassword: user.userPassword }
    return {
      // 使用 jwtService.sign() 基于 payload 生成 token 字符串
      access_token: this.jwtService.sign(payload),
    };


  }





















  async adduser(userDto: any): Promise<any> {


    const user = { wxID: userDto.wxID, userName: userDto.userName, userPassword: this.jwtService.sign(userDto.userPassword) }

    return await this.userRepository.save(user)
  }





  async findOneByName(userName: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        userName,
      },
    });
    if (!user) {
      throw new Error('user not found -- findOneByName');
    }
    return user;
  }


  async findAll(): Promise<UserEntity[]> {
    const users = await this.userRepository.find();
    return users;
  }


  /**
   * 添加用户
   */
  // async addAUser(userDto: any): Promise<any> {
  //   const { userName, wxID, userPassword } = userDto;
  //   const u = await this.userRepository.findOne({
  //     where: {
  //       userName,
  //     }
  //   })
  //   if (u) {
  //     return {
  //       errorCode: 1,
  //       errorInfo: "错误"
  //     }
  //   };
  //   return await this.userRepository.save({
  //     wxID,
  //     userName,
  //     userPassword,
  //     isActive: false,
  //   })
  // }

  async deleteUserByID(userID: string): Promise<any> {
    return await this.userRepository.delete({ id: userID })
  }


}
